<template>
  <div class="app-container">
    <!-- 顶部搜索栏 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.kw"
        placeholder="请输入支付文件名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.order_no"
        placeholder="请输入订单号"
        style="width: 200px; margin-left: 10px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        style="margin-left: 10px;"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        v-if="this.$store.getters.roles.indexOf('crm_user') !== -1"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加支付文件
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="支付文件名称" min-width="200px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="关联订单" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.crm_order && row.crm_order.order_no }}</span>
        </template>
      </el-table-column>

      <el-table-column label="项目" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.project && row.project.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="分类数量" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag type="info">{{ (row.categories && row.categories.length) || 0 }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="快捷访问" width="120px" align="center">
        <template slot-scope="{row}">
          <el-button
            v-if="row.token"
            type="text"
            size="small"
            icon="el-icon-link"
            @click="copyToken(row.token)"
          >
            复制链接
          </el-button>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        width="150px"
        align="center"
        prop="created_at"
        sortable="custom"
      >
        <template slot-scope="{row}">
          <span>{{ row.created_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            v-if="this.$store.getters.roles.indexOf('crm_user') !== -1"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total>0"
      background
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 创建/编辑对话框 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="90%"
      top="5vh"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 100%;"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付文件名称" prop="name">
              <el-input v-model="temp.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联订单号" prop="crm_order_no">
              <el-input v-model="temp.crm_order_no" placeholder="请输入订单号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="快捷访问Token">
              <el-input v-model="temp.token" placeholder="系统自动生成" readonly>
                <el-button slot="append" icon="el-icon-refresh" @click="generateToken">重新生成</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <!-- 订单信息显示 -->
      <div v-if="temp.id && temp.order_params_array && temp.order_params_array.length > 0" style="margin-top: 20px;">
        <el-divider>订单信息</el-divider>
        <div class="order-info-container">
          <el-row :gutter="20">
            <el-col
              v-for="(paramObj, index) in temp.order_params_array"
              :key="index"
              :span="8"
              style="margin-bottom: 15px;"
            >
              <div
                v-for="(value, key) in paramObj"
                :key="key"
                class="order-info-item"
              >
                <label class="order-info-label">{{ key }}:</label>
                <span class="order-info-value">{{ value || '无' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 通用类别参数组件 -->
      <div v-if="temp.id" style="margin-top: 20px;">
        <CommonCategoryParams
          ref="categoryParams"
          :model-type="'crmpaymentfile'"
          :object-id="temp.id"
          :visible="dialogFormVisible"
          :upload-directory="-1"
          :upload-keyword="'payment_file'"
          :show-a-i="true"
          :show-parameters-by-default="false"
          @category-created="handleCategoryCreated"
          @category-updated="handleCategoryUpdated"
          @category-deleted="handleCategoryDeleted"
        />

      </div>

      <!-- 提示信息：当支付文件未保存时 -->
      <div v-else-if="dialogStatus === 'create'" style="margin-top: 20px; text-align: center; color: #909399;">
        <el-alert
          title="请先保存支付文件基本信息，然后可以添加类别和参数"
          type="info"
          :closable="false"
          show-icon
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ (dialogStatus === 'create' && temp.id) ? '完成' : '取消' }}
        </el-button>
        <el-button
          v-if="!temp.id || dialogStatus === 'update'"
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >
          {{ dialogStatus === 'create' ? '保存支付文件' : '更新支付文件' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmpaymentfile'
import CommonCategoryParams from '@/views/crm/elements/commoncategoryparams'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'

export default {
  name: 'CRMPaymentFile',
  components: {
    CommonCategoryParams
  },
  directives: { waves },
  filters: {
    parseTime(time, cFormat) {
      return parseTime(time, cFormat)
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20,
        kw: undefined,
        order_no: undefined,
        order_by: 'created_at',
        order_desc: 1
      },
      temp: {
        id: undefined,
        name: '',
        crm_order_no: '',
        token: '',
        order_params: '',
        order_params_array: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑支付文件',
        create: '创建支付文件'
      },
      rules: {
        name: [{ required: true, message: '支付文件名称是必填项', trigger: 'blur' }],
        crm_order_no: [{ required: true, message: '关联订单号是必填项', trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 移除了默认分类相关的computed属性
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      const params = new URLSearchParams()

      Object.keys(this.listQuery).forEach(key => {
        if (this.listQuery[key] !== undefined && this.listQuery[key] !== '') {
          params.append(key, this.listQuery[key])
        }
      })

      Get(null, params.toString()).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      } else if (prop === 'created_at') {
        this.sortByCreatedAt(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.order_by = 'id'
        this.listQuery.order_desc = 0
      } else {
        this.listQuery.order_by = 'id'
        this.listQuery.order_desc = 1
      }
      this.handleFilter()
    },
    sortByCreatedAt(order) {
      if (order === 'ascending') {
        this.listQuery.order_by = 'created_at'
        this.listQuery.order_desc = 0
      } else {
        this.listQuery.order_by = 'created_at'
        this.listQuery.order_desc = 1
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '新支付文件',
        crm_order_no: '',
        token: '',
        order_params: '',
        order_params_array: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.generateToken()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj

      // 处理order_params字段 - 后端直接返回数组格式
      if (this.temp.order_params && Array.isArray(this.temp.order_params)) {
        this.temp.order_params_array = this.temp.order_params
      } else if (this.temp.order_params && typeof this.temp.order_params === 'string') {
        try {
          this.temp.order_params_array = JSON.parse(this.temp.order_params)
        } catch (e) {
          console.error('解析order_params失败:', e)
          this.temp.order_params_array = []
        }
      } else {
        this.temp.order_params_array = []
      }

      // 处理关联订单显示
      if (this.temp.crm_order && this.temp.crm_order.order_no) {
        this.temp.crm_order_no = this.temp.crm_order.order_no
      }

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)

          // 自动生成支付文件名称（如果为空或者是默认名称）
          if (!tempData.name || tempData.name === '' || tempData.name === '新支付文件') {
            if (tempData.crm_order_no) {
              tempData.name = `${tempData.crm_order_no}支付审核文件`
            } else {
              tempData.name = '支付审核文件'
            }
          }

          // 移除order_params_array字段，订单信息由后端自动填充
          delete tempData.order_params_array

          Post(tempData).then((response) => {
            // 更新temp对象的ID和相关信息，这样类别参数组件就能显示了
            this.temp.id = response.data.id
            this.temp.name = tempData.name

            // 如果后端返回了订单参数信息，更新到前端显示
            if (response.data.order_params) {
              this.temp.order_params = response.data.order_params
              if (Array.isArray(response.data.order_params)) {
                this.temp.order_params_array = response.data.order_params
              }
            }

            // 不立即关闭对话框，让用户可以添加类别参数
            this.$notify({
              title: '成功',
              message: '支付文件创建成功，现在可以添加类别和参数',
              type: 'success',
              duration: 3000
            })

            // 刷新列表数据
            this.getList()

            // 刷新类别参数组件
            this.$nextTick(() => {
              if (this.$refs.categoryParams) {
                // 强制刷新组件数据
                this.$refs.categoryParams.loadCategoriesAndParameters()
              }
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)

          // 移除order_params_array字段，订单信息由后端自动填充
          delete tempData.order_params_array

          Put(tempData.id, tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除该支付文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Delete(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      })
    },
    generateToken() {
      // 生成随机token
      this.temp.token = 'pf_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
    },
    copyToken(token) {
      const tokenUrl = `${window.location.origin}/payment-file/${token}`

      // 复制到剪贴板
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(tokenUrl).then(() => {
          this.$message.success('链接已复制到剪贴板')
        })
      } else {
        // 备用方案
        const textArea = document.createElement('textarea')
        textArea.value = tokenUrl
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        try {
          document.execCommand('copy')
          this.$message.success('链接已复制到剪贴板')
        } catch (err) {
          this.$message.error('复制失败，请手动复制：' + tokenUrl)
        }
        document.body.removeChild(textArea)
      }
    },

    // 类别参数组件事件处理
    handleCategoryCreated(category) {
      console.log('类别已创建:', category)
    },
    handleCategoryUpdated(category) {
      console.log('类别已更新:', category)
    },
    handleCategoryDeleted(category) {
      console.log('类别已删除:', category)
    },

    // 处理对话框关闭
    handleDialogClose(done) {
      // 如果是创建模式且已经保存了基本信息，提示用户
      if (this.dialogStatus === 'create' && this.temp.id) {
        this.$confirm('支付文件已创建，确定要关闭编辑窗口吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          done()
        }).catch(() => {
          // 取消关闭
        })
      } else {
        done()
      }
    }
  }
}
</script>

<style scoped>
.link-type {
  color: #409EFF;
  cursor: pointer;
}

.link-type:hover {
  color: #66b1ff;
}

.filter-container {
  padding-bottom: 10px;
}

.filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}

/* 订单信息显示样式 */
.order-info-container {
  background-color: #f9fafc;
  border-radius: 4px;
  padding: 20px;
  border: 1px solid #ebeef5;
}

.order-info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.order-info-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
  font-size: 14px;
}

.order-info-value {
  color: #303133;
  font-size: 14px;
  flex: 1;
}
</style>
